<template>
    <div>
      <!-- 导出按钮 -->
      <!-- <el-button type="primary" @click="exportExcel">数据导出</el-button> -->
      <el-dialog
        v-model="isShow"
        :title="operateType === 'add' ? '新增' : '更新'"
      >
        <!-- <Servicecenter/> -->
        <Servicecenter
          :formLabel="opertateFormLabel"
          :operateType="operateType"
          :form="operateForm"
          ref="form"
          :inline="true"
        ></Servicecenter>
        <div slot="footer" id="buttone" class="dialog-footer">
          <el-button class="userbtn" @click="isShow = false">取消</el-button>
          <el-button class="userbtn" type="primary" @click="confirm"
            >确定</el-button
          >
        </div>
      </el-dialog>
      <div class="headerbtn">
        <div class="leftbtn">
          <el-button
            type="primary"
            @click="Loadingdata"
            :loading-icon="Eleme"
            :loading="loading"
            >刷新数据</el-button
          >
          <el-dropdown>
            <el-button type="success">
              数据导出<el-icon class="el-icon--right"><arrow-down /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="exportExcel2">
                  <el-button type="success">
                    表格数据
                  </el-button></el-dropdown-item
                >
                <el-dropdown-item @click="exportExcel1">
                  <el-button type="success">原型数据</el-button></el-dropdown-item
                >
              </el-dropdown-menu>
            </template>
          </el-dropdown>
          <el-button type="warning" @Click="addinfo()">
            新增 &nbsp;<el-icon><Plus /></el-icon>
          </el-button>
        </div>
        <el-form :inline="true" class="demo-form-inline">
          <el-form-item label-width="50px" label="详情">
            <el-input
              v-model="search"
              size="default"
              placeholder="请输入关键信息"
              @keypress.enter="filterTableData"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="filterTableData"
              >查询</el-button
            >
          </el-form-item>
        </el-form>
      </div>
      <div class="tablebox">
        <el-table
          id="out-table"
          :data="listdata.slice((page - 1) * limit, page * limit)"
          style="width: 100%"
        >
          <el-table-column fixed prop="id" label="id" width="70" />
          <el-table-column prop="contact_name" label="活动主题" width="120" />
          <el-table-column prop="contact_address" label="活动地址" width="120" />
          <el-table-column prop="contact_unit" label="组织单位" width="120" />
          <el-table-column prop="contact_info" label="活动信息" width="120" />
          <el-table-column prop="contact_remarks" label="活动备注" width="120" />
          <el-table-column prop="contact_thoughts" label="活动感谢" width="120" />
          <el-table-column prop="contact_phone" label="联系电话" width="120" />
          <!-- <el-table-column prop="picture" label="City" width="320" /> -->
          <el-table-column prop="contact_time" label="举办时间" width="150" />
          <el-table-column prop="update_time" label="结束时间" width="150" />
          <!-- <el-table-column prop="cost_count" label="应缴费用" width="80" /> -->
          <el-table-column fixed="right" label="用户编辑"  width="250">
            <template #default="scope">
              <el-button
                type="primary"
                @click="edituser(scope.$index, scope.row)"
              >
                <el-icon><Edit /></el-icon>&nbsp; 修改
              </el-button>
              <el-button
                type="danger"
                @click="deleteruser(scope.$index, scope.row)"
              >
                <el-icon><Delete /></el-icon> &nbsp;删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          :currentPage="page"
          :page-size="limit"
          :page-sizes="[5, 10]"
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="TableDatatoal"
          @size-change="handleSizeChange"
          @current-change="CurrentChange"
        />
      </div>
    </div>
  </template>
  
  <script setup lang="ts">
  // 引入导出Excel表格依赖
  import * as FileSaver from "file-saver";
  import * as XLSX from "xlsx";
  import { Eleme } from "@element-plus/icons-vue";
  import {
    contactcreate,
    contactllilist,
    contactupdate,
    contactremove,
  } from "@/request/contact.ts";
  const list = reactive({
    listdata: [],
    limit: 5,
    page: 1,
    isShow: false,
    loading: false,
    operateType: "",
    operateForm: {
      id: "",
      contact_name: "",
      contact_address: "",
      contact_info: "",
      contact_unit: "",
      contact_remarks: "",
      contact_phone: "",
      contact_thoughts:"",
      contact_time: "",
      update_time: "",
    },
    editdata: "",
    opertateFormLabel: [
      {
        model: "id",
        label: "id",
        type: "id",
      },
      {
        model: "contact_name",
        label: "活动主题",
        type: "input",
      },
      {
        model: "contact_address",
        label: "活动地址",
        type: "input",
      },
      {
        model: "contact_unit",
        label: "组织单位",
        type: "input",
      },
      {
        model: "contact_info",
        label: "活动信息",
        type: "input",
      },
      {
        model: "contact_remarks",
        label: "活动备注",
        type: "input",
      },
      {
        model: "contact_phone",
        label: "联系电话",
        type: "input",
      },
      {
        model: "contact_thoughts",
        label: "活动感谢",
        type: "input",
      },
      {
        model: "contact_time",
        label: "举办时间",
        type: "date",
      },
      {
        model: "update_time",
        label: "结束时间",
        type: "date",
      },
    ],
  });
  const search = ref("");
  let {
    listdata,
    limit,
    page,
    isShow,
    operateForm,
    loading,
    operateType,
    editdata,
    opertateFormLabel
  } = toRefs(list);
  onMounted(() => {
    getawardlist();
  });
  const Loadingdata = () => {
    list.loading = true;
    setTimeout(() => {
      list.loading = false;
      getawardlist();
    }, 2000);
  };
  
  const getawardlist = async () => {
    let { result } = await contactllilist();
    // console.log("result", result);
    for (let i = 0; i < result.length; i++) {
      // const element = array[i];
      result[i].contact_time = result[i].contact_time.slice(0, 10);
      result[i].update_time = result[i].update_time.slice(0, 10);
    }
    list.listdata = result;
  };
  
  // 用户名搜索
  let filterTableData = (val) => {
    let arr = [];
    if (search.value) {
      for (let i = 0; i < list.listdata.length; i++) {
        for (let k in list.listdata[i]) {
          if (String(list.listdata[i][k]).indexOf(search.value) > -1) {
            arr.push(list.listdata[i]);
            break;
          }
        }
      }
      // console.log(arr);
    } else {
      arr = list.listdata;
    }
    list.listdata.length = arr.length;
    list.listdata = arr;
  };
  const goback = () => {
    list.isShow = false;
  };
  
  // 导出表格（原型）
  const exportExcel1 = async () => {
    let { result } = await contactllilist({ responseType: "blob" });
    const data = XLSX.utils.json_to_sheet(result); //此处tableData.value为表格的数据
    const dc = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(dc, data, "test-data"); //test-data为自定义的sheet表名
    XLSX.writeFile(dc, "test.xlsx"); //test.xlsx为自定义的文件名
  };
  const exportExcel2 = async () => {
    /* 从表生成工作簿对象 */
    var wb = XLSX.utils.table_to_book(document.querySelector("#out-table"));
    /* 获取二进制字符串作为输出 */
    var wbout = XLSX.write(wb, {
      bookType: "xlsx",
      bookSST: true,
      type: "array",
    });
    try {
      FileSaver.saveAs(
        //Blob 对象表示一个不可变、原始数据的类文件对象。
        //Blob 表示的不一定是JavaScript原生格式的数据。
        //File 接口基于Blob，继承了 blob 的功能并将其扩展使其支持用户系统上的文件。
        //返回一个新创建的 Blob 对象，其内容由参数中给定的数组串联组成。
        new Blob([wbout], { type: "application/octet-stream" }),
        //设置导出文件名称
        "idea.xlsx"
      );
    } catch (e) {
      if (typeof console !== "undefined") console.log(e, wbout);
    }
    return wbout;
  };
  
  watch([() => search.value], () => {
    if (search.value == "") {
      getawardlist();
    }
  });
  
  // 分页
  const TableDatatoal = computed(() => {
    // 该函数的返回值就是计算属性的值
    return list.listdata.length;
  });
  
  let handleSizeChange = (val) => {
    list.limit = val;
  };
  let CurrentChange = (val) => {
    list.page = val;
    // getuserlistinfo();
  };
  
  const addinfo = () => {
    list.operateType = "add";
    list.operateForm = {
      id: "",
      contact_name: "",
      contact_address: "",
      contact_info:"",
      contact_unit:"",
      contact_remarks: "",
      contact_phone: "",
      contact_time:"",
      contact_thoughts:"",
      update_time:"",
    };
    list.isShow = true;
  };
  const edituser = (index, row) => {
    // list.editdata = row;
    console.log(index, row);
    list.operateType = "edit";
    list.operateForm = {
      id: row.id,
      contact_name: row.contact_name,
      contact_address: row.contact_address,
      contact_info: row.contact_info,
      contact_unit: row.contact_unit,
      contact_remarks: row.contact_remarks,
      contact_phone: row.contact_phone,
      contact_thoughts: row.contact_thoughts,
      contact_time: row.contact_time,
      update_time: row.update_time,
    };
    list.isShow = true;
  };
  const deleteruser = async (index, row) => {
    console.log(row.id);
    let { id } = row;
    // await contactremove({id})
    await contactremove({
      id,
    }).then((res) => {
      let { code, result } = res;
      console.log(res);
  
      if (code == 200) {
        ElMessage({
          message: result,
          type: "success",
        });
        // getuserlist();
      } else {
        ElMessage({
          message: result,
          type: "error",
        });
      }
    });
    getawardlist();
  };
  
  
  const confirm =async ()=>{
    console.log(list.operateForm);
    if (list.operateType === "edit") {
     await contactupdate(list.operateForm).then(res=>{
      // console.log(res);
      let { code, message } = res;
        if (code === 200) {
          ElMessage({
            message: message,
            type: "success",
          });
        } else {
          ElMessage({
            message: message,
            type: "error",
          });
        }
      })
    }else{
     delete list.operateForm.id
     await contactcreate(list.operateForm).then(res=>{
      let { code, message } = res;
        if (code === 200) {
          ElMessage({
            message: message,
            type: "success",
          });
        } else {
          ElMessage({
            message: message,
            type: "error",
          });
        }
      })
    }
    await getawardlist()
    list.isShow = false;
  }
  
  </script>
  
  <style lang="scss" scoped>
  .drowbox {
    width: 100px;
    height: 40px;
    background-color: aqua;
    display: flex;
    flex-direction: row;
    justify-content: center;
  }
  
  :deep(.el-dropdown-menu) {
    width: 100px;
  }
  .headerbtn {
    width: 100%;
    height: 80px;
    display: flex;
    justify-content: space-between;
  }
  
  .leftbtn {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    width: 320px;
  }
  </style>
  